package utils

import (
	"MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/dto/request"
	"github.com/gin-gonic/gin"
)

func GetClaims(token string) (*request.MoClaims, error) {
	j := NewJWT(&CommonGin.AuthGroup.Bearer)
	claims, err := j.ParseToken(token)
	if err != nil {
		MoLogger.Error("从Gin的Context中获取从jwt解析信息失败, 请检查请求头是否存在x-token且claims是否为规定结构")
	}
	return claims, err
}

// GetUserID 从Gin的Context中获取从jwt解析出来的用户ID
func GetUserID(c *gin.Context, token string) uint64 {
	if claims, exists := c.Get("claims"); !exists {
		if cl, err := GetClaims(token); err != nil {
			return 0
		} else {
			return cl.BaseClaims.ID
		}
	} else {
		waitUse := claims.(*request.MoClaims)
		return waitUse.BaseClaims.ID
	}
}

// GetUserUuid 从Gin的Context中获取从jwt解析出来的用户ID
func GetUserId(c *gin.Context, token string) uint64 {
	if claims, exists := c.Get("claims"); !exists {
		if cl, err := GetClaims(token); err != nil {
			return 0
		} else {
			return cl.BaseClaims.ID
		}
	} else {
		waitUse := claims.(*request.MoClaims)
		return waitUse.BaseClaims.ID
	}
}

// GetUserInfo 从Gin的Context中获取从jwt解析出来的用户角色id
func GetUserInfo(c *gin.Context, token string) *request.MoClaims {
	if claims, exists := c.Get("claims"); !exists {
		if cl, err := GetClaims(token); err != nil {
			return nil
		} else {
			return cl
		}
	} else {
		waitUse := claims.(*request.MoClaims)
		return waitUse
	}
}

// GetUserName 从Gin的Context中获取从jwt解析出来的用户名
func GetUserName(c *gin.Context, token string) string {
	if claims, exists := c.Get("claims"); !exists {
		if cl, err := GetClaims(token); err != nil {
			return ""
		} else {
			return cl.Username
		}
	} else {
		waitUse := claims.(*request.MoClaims)
		return waitUse.Username
	}
}

func GetUsernameFromGin(c *gin.Context) string {
	claimsAny, _ := c.Get(consts.GinContext_Claims_Key)
	claim := claimsAny.(*request.MoClaims)
	return claim.Username
}

func GetUserIdFromGin(c *gin.Context) uint64 {
	claimsAny, _ := c.Get(consts.GinContext_Claims_Key)
	claim := claimsAny.(*request.MoClaims)
	return claim.BaseClaims.ID
}

func GetClaimsFromGin(c *gin.Context) *request.MoClaims {
	return c.MustGet(consts.GinContext_Claims_Key).(*request.MoClaims)
}
